package com.deep.seata.standalone.service.impl;

import com.deep.seata.standalone.mapper.OrdersMapper;
import com.deep.seata.standalone.mode.Orders;
import com.deep.seata.standalone.mode.Product;
import com.deep.seata.standalone.service.AccountService;
import com.deep.seata.standalone.service.ProductService;
import com.deep.seata.standalone.service.TestService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author dell
 * @create 2022/6/23 16:50
 */
@Slf4j
@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private AccountService accountService;

    @Autowired
    private ProductService productService;

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer createOrder(Map<String, Integer> params) throws Exception {
        Integer userId = Integer.valueOf(params.get("userId"));
        Integer productId = Integer.valueOf(params.get("productId"));
        //
        if (userId > 1) {
            throw new RuntimeException("服务tcc测试回滚");
        }

        Integer amount = 1; // 购买数量暂时设置为 1

        log.info("当前 XID: {}", RootContext.getXID());

        // 减库存 - 远程服务
        Product product = productService.reduceStock(productId, amount);

        // 减余额 - 远程服务
        accountService.reduceBalance(userId, product.getPrice());

        // 下订单 - 本地下订单
        Orders order = new Orders();
        order.setUserId(userId);
        order.setProductId(productId);
        order.setPayAmount(product.getPrice().multiply(new BigDecimal(amount)));

//        ordersMapper.insertSelective(order);

        Integer orderId = addOrder(order);

        log.info("下订单: {}", orderId);
//        int a = 1 / 0;
        // 返回订单编号

        return orderId;
     }

    @Override
    public boolean commitTcc(BusinessActionContext context) {
        System.out.println("commit------------------> xid =" + context.getXid());

        return false;
    }

    @Override
    public boolean cancel(BusinessActionContext context) {
        System.out.println("rollback------------------> xid =" + context.getXid());

        return false;
    }


    public Integer addOrder(Orders order) {
        ordersMapper.insertSelective(order);
        return order.getId();
    }
}
